#include <header.h>

int main(){

    char *port = "8080";
    char *ip = "0.0.0.0";

    int socket_fd = socket(AF_INET, SOCK_STREAM, 0);

    struct sockaddr_in  sock;
    sock.sin_family = AF_INET;
    sock.sin_port = htons(atoi(port));
    sock.sin_addr.s_addr = inet_addr(ip);
    bind(socket_fd, (struct sockaddr *)&sock, sizeof(sock));


    listen(socket_fd, 10);

    int net_fd = accept(socket_fd, NULL, NULL);

    while(1){
        fd_set set;
        FD_ZERO(&set);
        FD_SET(STDIN_FILENO, &set);
        FD_SET(net_fd, &set);

        select(net_fd+1, &set, NULL, NULL, NULL);

        if(FD_ISSET(STDIN_FILENO, &set)){
            char buf[100] = {0};
            read(STDIN_FILENO, buf, sizeof(buf));
            send(net_fd, buf, sizeof(buf), 0);

        }
        if(FD_ISSET(net_fd, &set)){
            // 发现socket可读
            char buf[100] = {0};
            ssize_t  ret = recv(net_fd, buf, sizeof(buf), 0);
            if(ret == 0){
                // 可读-> 没有读到数据
                // -> 对断开链接

                printf("对方断开链接 \n");
                break;
            }
            printf("buf: %s \n", buf);

        }
    }

    close(net_fd);
    close(socket_fd);
    return 0;
}

